# @Time : 2024-11-07 11:43
# @Author : Fioman 
# @Phone : 13149920693
"""
多进程: CPU计算使用多进程效率比较高,优于多线程.
多线程: IO操作的时候,多线程会优于多进程,因为I/O操作没有GIL(全局解释器锁的限制)
"""
import time
from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor

"""
例子:
分别使用多进程和多线程来计算斐波拉切数列的值,看看耗时情况
"""


def fib(n):
    if n <= 2:
        return 1
    return fib(n - 1) + fib(n - 2)


if __name__ == '__main__':
    start = 20
    end = 40
    with ThreadPoolExecutor() as executor:
        calcStart = time.time()
        futures = [executor.submit(fib, n) for n in range(start, end)]
        for future in as_completed(futures):
            print(f"结果: {future.result()}")

        print(f"多线程计算耗时: {time.time() - calcStart}")

    with ProcessPoolExecutor() as executor:
        calcStart = time.time()
        futures = [executor.submit(fib, n) for n in range(start, end)]
        for future in as_completed(futures):
            print(f"结果: {future.result()}")
    print(f"多进程计算耗时: {time.time() - calcStart}")
